package main

import (
	"fmt"
	"github.com/hashicorp/consul/api"
	_ "github.com/satori/go.uuid"
	uuid "github.com/satori/go.uuid"
	"go.uber.org/zap"
	"google.golang.org/grpc"
	"google.golang.org/grpc/health"
	"google.golang.org/grpc/health/grpc_health_v1"
	"net"
	"os"
	"os/signal"
	"shop/user-srv/global"
	"shop/user-srv/handler"
	"shop/user-srv/initialize"
	"shop/user-srv/proto"
	"syscall"
)

func main() {
	//IP := flag.String("ip", "0.0.0.0", "ip地址")
	//Port := flag.Int("port", 50052, "端口号")
	//flag.Parse()
	//fmt.Println("ip:", *IP)
	//fmt.Println("port:", *Port)

	initialize.InitLogger()
	initialize.InitConfig()
	initialize.InitDb()
	server := grpc.NewServer()
	//注册服务健康检查
	grpc_health_v1.RegisterHealthServer(server, health.NewServer())

	Ip := global.ServerConfig.Ip     //服务的ip地址
	Port := global.ServerConfig.Port //服务的端口
	//consul服务注册
	cfg := api.DefaultConfig()
	cfg.Address = fmt.Sprintf("%s:%s", global.ServerConfig.ConsulConfig.Host, global.ServerConfig.ConsulConfig.Port)
	fmt.Println(cfg.Address, "ddra")
	client, err := api.NewClient(cfg)
	if err != nil {
		panic(err)
	}
	_ = &api.AgentServiceCheck{
		//GRPC:                           "http://127.0.0.1:8301/health",
		HTTP:                           "http://127.0.0.1:8301/health",
		Timeout:                        "5s",
		Interval:                       "5s",
		DeregisterCriticalServiceAfter: "10s",
	}

	serverId := uuid.NewV4().String()
	registration := new(api.AgentServiceRegistration)
	registration.Name = global.ServerConfig.Name
	registration.Address = Ip
	registration.Tags = []string{"goods"}
	registration.Port = Port
	registration.ID = serverId
	//registration.Check = check

	err = client.Agent().ServiceRegister(registration)
	if err != nil {
		panic(err)
	}

	proto.RegisterUserServer(server, &handler.UserServer{})
	//fmt.Println(fmt.Sprintf("%s:%s", *IP, *Port), "##")
	listen, err := net.Listen("tcp", fmt.Sprintf("%s:%d", Ip, Port))
	if err != nil {
		panic("failed to listen" + err.Error())
	}
	//defer listen.Close()
	go func() {
		err = server.Serve(listen)
		if err != nil {
			panic("failed to start grpc:" + err.Error())
		}
	}()

	quit := make(chan os.Signal)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	if err = client.Agent().ServiceDeregister(serverId); err != nil {
		zap.S().Info("注销失败")
	} else {
		zap.S().Info("注销成功")
	}

}
